package main

import (
	"sync"
	"os"
	"time"
	"fmt"
	"syscall"
	"os/signal"
)


func main() {
	// case0()
	// case1()
	// case2()
	// case3()
	case4()
}

func Producer(factor int, out chan<- int) {
	for i :=0; ;i++ {
		out <- i*factor
	}
}

func Consumer(in <-chan int) {
	for v := range in {
		fmt.Println(v)
	}
}

func case0() {
	ch := make(chan int, 64) //成果队列

	go Producer(3, ch)
	go Producer(5, ch)
	go Consumer(ch)
	
	time.Sleep(5 * time.Second)
}

func case1() {
		
	ch := make(chan int, 64)

	go Producer(3, ch)
	go Producer(5, ch)
	go Consumer(ch)
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
	fmt.Println("quit (%v)\n", <-sig)
}


func case2() {
	input := make(chan int, 64)
    t1 := time.NewTimer(time.Second * 5)
    t2 := time.NewTimer(time.Second * 10)
	for {	
        select {
        case msg :=<- input:
			println(msg)
        case <-t1.C:
            println("5s timer")
            t1.Reset(time.Second * 5)

        case <-t2.C:
            println("10s timer")
            t2.Reset(time.Second * 10)
        }
    }
}

func worker(cannel chan bool) {
	for {
		select {
		default:
			fmt.Println("hello")
		case<-cannel:
		}
	}
}

func case3() {
	cancel := make(chan bool)

	for i:=0; i<10; i++ {
		go worker(cancel)
	}

	time.Sleep(time.Second)
	close(cancel)
}

func worker2(wg *sync.WaitGroup, cannel chan bool) {
	defer wg.Done()
	for {
		select {
		default:
			fmt.Println("hello")
		case<-cannel:
			return
		}
	}
}
func case4() {
	cannel := make(chan bool)

	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go worker2(&wg, cannel)
	}

	time.Sleep(time.Second)
	close(cannel)
	wg.Wait()
}